<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { createProductsChildrenApi, updateProductsChildrenApi, getProductsChildrenDetailApi } from "@/api/products"
import { type CreateOrUpdateProductsChildrenRequestData } from "@/api/products/types"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { useRouter } from "vue-router"
import { getBasePath } from "@/api/common/index"
import UploadImageList from "@/components/UploadImageList/index.vue"
import FormAddItem from "@/components/FormAddItem/index.vue"
import BuildTypeSelect from "../components/BuildTypeSelect.vue"
import IEditor from "@/components/IEditor/index.vue"

defineOptions({
  // 命名当前组件
  name: "ProductChildrenOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const category_id: string = router.currentRoute.value.params.categoryId as string

const loading = ref<boolean>(false)

const gotoList = () => {
  router.push("/products/children")
}
//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateProductsChildrenRequestData = {
  id,
  name: "",
  img_list: [],
  category_id: "",
  build_type_id: "",
  desc: "",
  tag: "",
  introduction: "",
  usage: "",
  params: [],
  name_en: "",
  desc_en: "",
  tag_en: "",
  introduction_en: "",
  usage_en: "",
  params_en: []
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateProductsChildrenRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateProductsChildrenRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入产品名称" }],
  img_list: [{ required: true, trigger: "blur", message: "请上传产品图片" }],
  introduction: [{ required: true, trigger: "blur", message: "请上传产品简介" }],
  tag: [{ required: true, trigger: "blur", message: "请输入产品标签" }],
  desc: [{ required: true, trigger: "blur", message: "请输入产品描述" }],
  usage: [{ required: true, trigger: "blur", message: "请输入产品用途" }],
  params: [{ required: true, trigger: "blur", message: "请输入产品参数" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createProductsChildrenApi : updateProductsChildrenApi
    const img_list = JSON.stringify(formData.value.img_list)
    const params = JSON.stringify(formData.value.params)
    const params_en = JSON.stringify(formData.value.params_en)
    formData.value.tag = formData.value.tag?.replace(/，/g, ",")
    formData.value.tag_en = formData.value.tag_en?.replace(/，/g, ",")
    api({
      ...formData.value,
      category_id,
      img_list,
      params,
      params_en
    })
      .then(() => {
        ElMessage.success("操作成功")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

//#region 查
const getProductsDetail = () => {
  if (!id) {
    return
  }
  getProductsChildrenDetailApi(id)
    .then(async ({ data }) => {
      formData.value = data
      formData.value.img_list = JSON.parse(formData.value.img_list)
      formData.value.params = JSON.parse(formData.value.params)
      formData.value.params_en = JSON.parse(formData.value.params_en)
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
const basePath = ref<string>("")
onMounted(async () => {
  getProductsDetail()
  const { data } = await getBasePath()
  basePath.value = data
})
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined ? "新增产品" : "修改产品" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="200px" label-position="left">
        <el-form-item prop="name" label="产品名称">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name_en" label="产品名称(英文)">
          <el-input v-model="formData.name_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="build_type_id" label="建筑类型">
          <BuildTypeSelect v-model="formData.build_type_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="tag" label="产品标签">
          <el-input v-model="formData.tag" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="tag_en" label="产品标签(英文)">
          <el-input v-model="formData.tag_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="desc" label="产品描述">
          <el-input v-model="formData.desc" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="desc_en" label="产品描述英文">
          <el-input v-model="formData.desc_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="img_list" label="产品图片列表">
          <upload-image-list v-model="formData.img_list" />
        </el-form-item>
        <el-form-item prop="introduction" label="产品简介">
          <IEditor v-model="formData.introduction" />
        </el-form-item>
        <el-form-item prop="introduction_en" label="产品简介(英文)">
          <IEditor v-model="formData.introduction_en" />
        </el-form-item>
        <el-form-item prop="usage" label="产品用途">
          <IEditor v-model="formData.usage" />
        </el-form-item>
        <el-form-item prop="usage_en" label="产品用途(英文)">
          <IEditor v-model="formData.usage_en" />
        </el-form-item>
        <form-add-item
          v-model="formData.params"
          paramName="params"
          param-key="产品参数"
          param-value="产品参数值"
          addText="添加产品参数"
        />
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
